import { Toast } from 'vant'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect:'/home'
  },
  {
    path:'/home',
    name:'home',
    component:() => import('@/views/home/Home.vue')
  },
  {
    path: '/cate',
    name: 'cate',
    component: () => import('@/views/cate/Cate.vue')
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('@/views/cart/Cart.vue')
  },
  {
    path: '/detail/:id',
    name: 'detail',
    component: () => import('@/views/detail/Detail.vue')
  },
  {
    path: '/goodsList/:query',
    name: 'goodsList',
    component: () => import('@/views/goods_list/GoodsList.vue')
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/search/Search.vue')
  },
  {
    path: '/addressList',
    name: 'addressList',
    component: () => import('@/views/addressList/AddressList.vue')
  },
  {
    path: '/addressEdit/:action',
    name: 'addressEdit',
    component: () => import('@/views/addressEdit/AddressEdit.vue')
  },
  {
    path: '/userInfo',
    name: 'userInfo',
    component: () => import('@/views/my/UserInfo.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/my/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/my/Register.vue')
  },
  {
    path: '/hide',
    name: 'hide',
    component: () => import('@/views/my/Hide.vue')
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to  , from,  next) => {
  let token = JSON.parse(sessionStorage.getItem('token'))
  if(!token){
    if (to.path === '/cart' || to.path === '/userInfo'){
      next('/hide')
    }
    else{
      next()
    }
  }
  else{
    next()
  }
})


// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
// push
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}



// replace
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

export default router
